package cn.wwcyc.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.wwcyc.domain.UploadFile;
import cn.wwcyc.service.UploadFileService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${files.upload.path}")
    private String fileUploadPath;
    @Autowired
    UploadFileService uploadFileService;

    @PostMapping ("/upload")
    public String fileupload(@RequestParam MultipartFile file) throws IOException {
        String originFileName = file.getOriginalFilename();
        Long size = file.getSize();

        File uploadFileParentDir = new File(fileUploadPath);
        if(!uploadFileParentDir.exists()) {
            uploadFileParentDir.mkdir();
        }

        //添加uuid处理文件同名
        String savename = IdUtil.fastUUID() + "_" + originFileName;
        //hash打散
        int hCode = originFileName.hashCode();
        String hex = Integer.toHexString(hCode);
        String savePath = hex.charAt(0) +"/" + hex.charAt(1);
        File dirFile = new File(uploadFileParentDir,  savePath);
        dirFile.mkdirs();
        File destFile = new File(dirFile, savename);
        file.transferTo(destFile);
        //用MD5检查是否有重复的文件，如果有就只保存一个。避免保存重复的文件。
        String md5 = SecureUtil.md5(destFile);
        QueryWrapper<UploadFile> qw = new QueryWrapper<>();
        qw.eq("md5", md5);
        List<UploadFile> dbFiles = uploadFileService.list(qw);
        UploadFile dbFile = dbFiles.get(0);
        if(dbFile != null){//已经存在重复的文件了
            destFile.delete();
            savePath = dbFile.getSavePath();
            savename = dbFile.getSaveName();
        }
        //文件信息存入数据库
        UploadFile uploadFile = new UploadFile();
        uploadFile.setSize(size);
        uploadFile.setOriginName(originFileName);
        uploadFile.setSavePath(savePath);
        uploadFile.setSaveName(savename);
        uploadFile.setMd5(md5);
        uploadFileService.save(uploadFile);

        return savePath + savename;

    }

    @GetMapping("/{filename}")
    public void download(@PathVariable String filename, HttpServletResponse response) throws IOException {
//        String saveName = filepath.substring(filepath.lastIndexOf("/"));
//        System.out.println("in download------------------------------------------");
        QueryWrapper<UploadFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("save_name", filename);
        UploadFile uploadFileInfo = uploadFileService.getOne(queryWrapper);

        File uploadFile = new File(fileUploadPath + uploadFileInfo.getSavePath() + "/" +filename);
        ServletOutputStream os = response.getOutputStream();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(uploadFileInfo.getOriginName(), "utf-8"));

        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }
}
